package com.yunda.rfid_library;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * copyright (C), 2022, 运达科技有限公司
 * fileName NFCUtils
 *
 * @author 王玺权
 * date 2022-05-17 17:24
 * description
 * history
 */
public enum NFCUtils {
    //使用单例
    INSTANCE;
    String TAG=getClass().getSimpleName();
    /**
     * 声明一个nfc的Adapter
     */
    private NfcAdapter mNfcAdapter =null;

    /**
     * 读取数据
     */
    private String readInfo="";
    /**
     * 当前Activity
     */
    private Activity mActivity;

    /**
     * 读取或写入成功一次，置为read
     */
    private Boolean read=true;
    /**
     * 写入信息
     */
    private String writeMsg="";

    private NdefMessage ndefMessage;

    private  Ndef ndef;
    /**
     * 检查NFC是否可用
     * @param activity
     * @return
     */
    public Boolean CheckNFC(Activity activity){
        this.mActivity=activity;
//        if(mNfcAdapter==null){
        mNfcAdapter = NfcAdapter.getDefaultAdapter(activity);
//        }
        if (mNfcAdapter == null) {
            Log.e(TAG,"如果获取的mNfcAdapter=null，则说明该手机不支持nfc功能");
            Toast.makeText(activity,"该设备不支持nfc功能",Toast.LENGTH_SHORT).show();
            return false;
        }else {
            //如果手机有nfc功能，进一步判断nfc是否打开
            if (!mNfcAdapter.isEnabled()) {
                //假如手机的nfc功能没有被打开。则跳到打开nfc功能的界面
                Intent setNfc = new Intent(Settings.ACTION_NFC_SETTINGS);
                activity.startActivity(setNfc);
                Log.e(TAG,"假如手机的nfc功能没有被打开。则跳到打开nfc功能的界面");
                Toast.makeText(activity,"请在设置中打开nfc功能",Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    /**
     * 配合窗口生命周期
     */
    public void onResume(){
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                mActivity, 0, new Intent(mActivity, mActivity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if(mNfcAdapter!= null){
            mNfcAdapter.enableForegroundDispatch(mActivity, pendingIntent, nfcIntentFilter, null);
        }
    }

    public void onPause() {
        if(mNfcAdapter!= null){
            mNfcAdapter.disableForegroundDispatch(mActivity);
        }

    }


    /**
     * NFC扫描返回
     * @param intent
     */
    public void onNewIntent(Intent intent,Boolean isRead) throws IOException {
        read=isRead;
        readInfo="";
        ndef=null;
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Log.d("NFC", "onNewIntent: " + intent.getAction());
        if (tag != null) {
            if(ndef!=null){
                ndef.close();
            }
            ndef = Ndef.get(tag);
            try {
                ndef.connect();
                ndefMessage = ndef.getNdefMessage();

                if(read){
                    ReadNFC();
                }else {
//                    WriteNFC(writeMsg);
                }



            } catch (IOException | FormatException e) {
                e.printStackTrace();

            }finally {
                if(ndef!=null){
                    ndef.close();
                }

            }

        }
    }

    /**
     * 读取NFC信息
     * @return
     */
    public void  ReadNFC() throws IOException {
        read=true;
        try {
            readInfo = new String(ndefMessage.getRecords()[0].getPayload());
            Log.e("readFromNFC", "readFromNFC: "+readInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            ndef.close();
        }

    }

    public String  getReadInfo() {
        read=true;
        return readInfo;
    }


    /**
     * 写入NFC信息
     * @return
     */
    public Boolean WriteNFC(String message) throws IOException {
        if(TextUtils.isEmpty(message)){
            Toast.makeText(mActivity,"写入参数不能为空",Toast.LENGTH_SHORT).show();
            return false;
        }
        read=false;
        this.writeMsg=message;
        AtomicBoolean atomicBoolean=new AtomicBoolean(true);
        try {
            if(ndef!=null){
                ndef.close();
            }
            ndef.connect();
            NdefRecord mimeRecord = NdefRecord.createMime("text/plain", message.getBytes(Charset.forName("US-ASCII")));
            ndef.writeNdefMessage(new NdefMessage(mimeRecord));
            Log.e("readFromNFC", "标签写入成功: "+message);

        } catch (FormatException | IOException e) {
            e.printStackTrace();
            Log.e("readFromNFC", "标签写入失败: "+message);
            atomicBoolean.set(false);
        }finally {
            ndef.close();
        }
        return atomicBoolean.get();
    }
    public void setRead(Boolean mRead){
        this.read=mRead;
    }
}
